var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;

let startTime = 0;
let endTime = 0;
function getNowMonth() {
    $.ajax({
        async:false,
        type: 'POST',
        url: 'number/getNowMonthNew',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        success: function (res) {
            if (res.status == 200) {
                if (res.data != "") {
                    startTime = res.data.startDate;
                    endTime = res.data.endDate;
                }
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        },
        error: function (data) {
            layer.msg(data.msg, {icon: 5});
        }
    });
}

getNowMonth();

let endDate= laydate.render({
    elem: '#endCreateTime',//选择器结束时间
    type: 'date',
    value : new Date(endTime),
    min:"1970-1-1",//设置min默认最小值
    done: function(value,date){
        startDate.config.max={
            year:date.year,
            month:date.month-1,
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds : 0
        }
    }
});

let startDate=laydate.render({
    elem: '#startCreateTime',
    type: 'date',
    value : new Date(startTime),
    max:"2099-12-31",//设置一个默认最大值
    done: function(value, date){
        endDate.config.min ={
            year:date.year,
            month:date.month-1,
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds : 0
        };
    }
});

let userList = [];//操作人

//操作员、业务员
$.ajax({
    type : 'POST',
    url:'user/getAllUserNameAndCode',
    dataType:"json",
    contentType: 'application/json;charset=utf-8',
    success:function(res){
        if(res.status == 200){
            if(res.data){
                userList = res.data;
                for(let i in res.data){
                    $('#executorCode').append(new Option(res.data[i].name, res.data[i].code));
                    $('#salesmanCode').append(new Option(res.data[i].name, res.data[i].code));
                }
                form.render('select');
            }else{
                layer.msg(res.msg,{icon:0});
            }
        }else{
            layer.msg(res.msg,{icon:4});
        }
    }
});

let currencyList = getdictionary(5,14);//币种
let unitList = [];//制单公司列表
//制单公司
$.ajax({
    type : 'POST',
    url:'company/getAllMakerUnit',
    dataType:"json",
    contentType: 'application/json;charset=utf-8',
    success:function(res){
        if(res.status == 200){
            if(res.data){
                unitList = res.data;
                for(let i in res.data){
                    $('#unitSelect').append(new Option(res.data[i].name, res.data[i].code));
                }
                form.render('select');
            }else{
                layer.msg(res.msg,{icon:0});
            }
        }else{
            layer.msg(res.msg,{icon:4});
        }
    }
});
form.render();//表单刷新
layer.ready(function () {
    table.render({
        elem: '#customercomplaintselect'
        ,url: 'complaint/selectList'
        ,method:'post'
        ,request: {
            pageName: 'pageNum'
            ,limitName: 'pageSize'
        }
        ,contentType: 'application/json;charset=utf-8'
        ,toolbar: '#customercomplainttoolbar'
        ,id: 'customercomplainttableid'
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field:'oddNumber',width:170, title:'客诉单号',sort:true,event: "customercomplaintnumber"}
            ,{field:'customerName', title:'客户名称'}
            // ,{field:'salesContractNo', title:'销售合同号',sort:true}
            ,{field:'complaintUnit', title:'制单公司',
                templet: function(data) {
                    let name = "";
                    $.each(unitList, function(index, item) {
                        if (data.complaintUnit==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    if (name==""){
                        name = data.complaintUnit;
                    }
                    return name;
                }
            }
            ,{field:'isEstablish', title:'客诉成立否', templet: function(d) {return d.isEstablish==1?"是":"否";}}
            ,{field:'responsibleParty', title:'责任方'}
            ,{field:'currency', title:'币种',
                templet: function(data) {
                    let name = "";
                    $.each(currencyList, function(index, item) {
                        if (data.currency==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }
            ,{field:'salesman', title:'业务员',
                templet: function(data) {
                    let name = "";
                    $.each(userList, function(index, item) {
                        if (data.salesman==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }
            ,{field:'executor', title:'操作员',
                templet: function(data) {
                    let name = "";
                    $.each(userList, function(index, item) {
                        if (data.executor==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }
            ,{field:'createTime', title:'创建日期',sort:true,width: 185,templet: function(d) {return layui.util.toDateString(d.createTime,"yyyy-MM-dd");}}
            ,{field:'boxStatus', title:'单据类型', templet: function(data) {
                    switch (data.boxStatus) {
                        case "1": return "草稿箱";
                        case "2": return "待批箱";
                        case "3": return "已批箱";
                        case "4": return "完成箱";
                        case "5": return "垃圾箱";
                    }
                }
            }
            ,{fixed: 'right', width:240, toolbar: '#customercomplainteditor', title:'操作'}
        ]]
        ,height: $(document).height() - $('#customercomplaintselect').offset().top - 50
        ,page: true
        ,parseData: function(res){
            let code = 0 , count = 0, data = null;
            if(res.status!=200 &&res.status!=0){
                layer.msg(res.msg);
            }else{
                code = res.status;
                count = res.total;
                data = res.data;
            }
            return {
                "code": code,
                "count": count,
                "data": data
            }
        }
    });

});
table.on('tool(customercomplainttable)', function(obj){
    var data = obj.data;
    if(obj.event === 'update') {
        parent.intab("views/jsp/other/tpl/newupcustomercomplaint.jsp?id="+obj.data.id,"修改客诉")
    }else if(obj.event === 'delect'){
        layer.confirm('确定删除吗', function (index) {
            if(deleteById(data.id)){
                obj.del();
                layer.close(index);
            }
        });
        return;
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', function (index) {
            update(data.id,data.boxStatus*1+1,"提交审批");
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', function (index) {
            update(data.id,data.boxStatus*1+1,"审批通过");
        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定审批退回吗', function (index) {
            update(data.id,data.boxStatus-1,"审批退回");
        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', function (index) {
            update(data.id,data.boxStatus*1+1,"审批完成");
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', function (index) {
            update(data.id,1,"审批还原");
        });
    }else if (obj.event === "customercomplaintnumber"){
        parent.intab("views/jsp/other/tpl/viewcustomercomplaint.jsp?id="+obj.data.id,"客诉明细")
    }
});

form.on('submit(submitform)', function(data){
    table.reload('customercomplainttableid',{where: data.field });
    return false;
});

table.on('toolbar(customercomplainttable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/other/tpl/newupcustomercomplaint.jsp","新增客诉")
            break;
        case 'dels':
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.id);
            });
            if(delList.length>0){
                layer.confirm('确定删除所选项吗？',function (index) {
                    var cbList = table.cache["customercomplainttableid"];
                    for(var i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined"&&item == cbList[i].id) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("customercomplainttableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});

$("#statistical").on("click",function () {
    parent.intab("views/jsp/other/tpl/statistics.jsp","客诉统计")
});


function deleteById(delId) {
    var tf = false;
    $.ajax({
        type: 'POST',
        url: 'complaint/delete/'+delId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if(res.data){
                    tf = true;
                    layer.msg("删除成功",{icon: 1});
                    table.reload('customercomplainttableid');
                }else{
                    layer.msg("删除失败",{icon: 4});
                }
            }else{
                layer.msg("删除失败",{icon: 2});
            }
        },
        error: function (data) {
            layer.msg("删除异常",{icon: 5});
        }
    });
    return tf;
}

//boxStatus 1 草稿 2 待批  3:已批 4 完成 5 垃圾
function update(id,boxStatus,titleName) {
    var tf = false;
    var msgInfo = "";
    var dataJson = {
        "id":id,
        "boxStatus":boxStatus
    };
    $.ajax({
        type: 'POST',
        data: JSON.stringify(dataJson),
        url: 'complaint/updateBoxStatusBykey',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = true;
                msgInfo = titleName+"成功!"
                table.reload('customercomplainttableid');
            }else{
                msgInfo = titleName+"失败!"
            }
        },
        error: function (data) {
            msgInfo = titleName+"异常!"
        }
    });
    layer.msg(msgInfo);
    return tf;
}